#!/bin/bash
 echo "将现有的nameserver行替换为阿里云公共DNS"
# 检查是否具有root权限
if [ "$(id -u)" != "0" ]; then
  echo "此脚本需要root权限运行，请使用sudo或以root用户身份执行"
  exit 1
fi

INTERFACE="eth0"
DNS_SERVERS=("223.5.5.5" "223.6.6.6")
# 检测新设置是否生效
check_dns_effective() {
# 确保系统已安装dnsutils包（包含dig工具）
dpkg -s dnsutils &> /dev/null
if [ $? -ne 0 ]; then
  echo "正在安装dnsutils..."
  sudo apt update
  sudo apt install -y dnsutils || {
    echo "安装dnsutils失败，请手动安装（sudo apt update && sudo apt install -y dnsutils）。"
    exit 1
  }
fi
DOMAIN="github.com"
DNS_RESOLVED=$(dig +short @${DNS_SERVERS[0]} $DOMAIN)
if [[ ! -z "$DNS_RESOLVED" ]]; then
    echo "新设置的DNS服务器已成功解析域名：$DOMAIN -> $DNS_RESOLVED"
else
    echo "警告：新设置的DNS服务器无法正确解析域名：$DOMAIN"
fi
}

# 尝试通过NetworkManager更改DNS服务器
nmcli con mod "$INTERFACE" ipv4.dns "${DNS_SERVERS[@]}" > /dev/null 2>&1
if [ $? -eq 0 ]; then
  systemctl restart NetworkManager
  echo "已成功通过NetworkManager将DNS服务器更改为 ${DNS_SERVERS[*]}"
  echo "通过nmcli con mod $INTERFACE ipv4.dns ${DNS_SERVERS[@]} 命令"
  echo "检测DNS服务器设置是否生效------------------"
  check_dns_effective
else
  # 如果NetworkManager命令失败，则尝试通过systemd-resolved更改
  sed -i "s/^DNS=.*/DNS=${DNS_SERVERS[*]}/" /etc/systemd/resolved.conf
  if [ $? -eq 0 ]; then
    systemctl restart systemd-resolved.service
    echo "已成功通过systemd-resolved将DNS服务器更改为 ${DNS_SERVERS[*]}"
     echo "修改地址为/etc/systemd/resolved.conf（直接修改/etc/resolved.conf可能会被覆盖）"
     echo "检测DNS服务器设置是否生效------------------"
    check_dns_effective
  else
    echo "无法通过当前网络管理工具更改DNS服务器，请手动检查配置文件（直接修改/etc/resolved.conf）。"
  fi
fi